package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDtao;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    /**
     * 用户登录
     * 1.xxxxx
     * 2..xxxx
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDtao dto) {
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            //1.登录访问
            //根据电话查询记录
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //用户不存在
            if (apUser == null){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //登录的密码
            String loginPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            //密码错误
            if (!loginPassword.equals(apUser.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //密码正确
            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            //封装返回结果
            Map<String,Object> map = new HashMap<>();
            apUser.setPassword(null);
            apUser.setSalt(null);
            map.put("user", apUser);
            map.put("token", token);
            return ResponseResult.okResult(map);
        } else {
            //2.不登录访问
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
